package com.yejiali.backend.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.yejiali.backend.common.constant.SystemConstant;
import com.yejiali.backend.entity.CommentLike;
import com.yejiali.backend.entity.Comments;
import com.yejiali.backend.entity.Users;
import com.yejiali.backend.entity.Videos;
import com.yejiali.backend.entity.vo.CommentLikeVO;
import com.yejiali.backend.mapper.CommentLikeMapper;
import com.yejiali.backend.mapper.CommentsMapper;
import com.yejiali.backend.mapper.UsersMapper;
import com.yejiali.backend.mapper.VideosMapper;
import com.yejiali.backend.response.Response;
import com.yejiali.backend.service.CommentLikeService;
import com.yejiali.backend.util.MessageUtil;
import com.yejiali.backend.util.RedisUtil;
import com.yejiali.backend.ws.WebSocketServer;
import jakarta.websocket.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 点赞表(CommentLike)表服务实现类
 *
 * @author yejiali
 * @since 2025-08-16 10:05:05
 */
@Service
public class CommentLikeServiceImpl extends ServiceImpl<CommentLikeMapper, CommentLike> implements CommentLikeService {

    @Autowired
    private UsersMapper usersMapper;

    @Autowired
    private CommentsMapper commentsMapper;

    @Autowired
    private RedisUtil redisUtil;



    /**
     * 删除收到的评论点赞通知
     * @param commentLikeId
     * @return
     */
    @Override
    public Response<String> deleteLikeComment(Long commentLikeId) {
        //查看是否存在
        CommentLike commentLike = this.getById(commentLikeId);
        if(commentLike == null || commentLike.getIsDeleted() == 1){
            return Response.error(400,"评论点赞已被删除");
        }
        //删除
        commentLike.setIsDeleted(1);
        this.updateById(commentLike);
        return Response.success("删除成功");
    }

    /**
     * 点赞评论
     * @param userId
     * @return
     * 1.在reids（Set）中判断是否已点赞
     * 2.未命中，在数据库中查询，已点赞则同步到redis中
     * 3.为点赞，在数据库中插入记录，同步到redis中，点赞数+1
     * 4.通知被赞用户
     */
    @Override
    public Response<String> likeComment(Long userId, Long commentId) throws JsonProcessingException {
        //user是否存在
        Users users = usersMapper.selectById(userId);
        if(users == null){
            return Response.error(400,"用户不存在");
        }
        //comment是否存在
        Comments comments = commentsMapper.selectById(commentId);
        if(comments == null){
            return Response.error(400,"评论不存在");
        }
        // Redis 中查看是否有记录
        String key = "comment:like:" + commentId;
        if (redisUtil.sHasKey(key, userId)) {
            return Response.error(400, "已点赞");
        }
        // 在数据库中查询是否已点赞
        QueryWrapper<CommentLike> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        queryWrapper.eq("comment_id", commentId);
        CommentLike commentLike = this.getOne(queryWrapper);
        if (commentLike != null) {
            // 同步到 Redis
            redisUtil.sSet(key, userId);
            return Response.error(400, "已点赞");
        }
        // 未点赞，插入记录
        commentLike = CommentLike.builder()
                .userId(userId)
                .accepterId(comments.getPublisherId())
                .commentId(commentId)
                .build();
        this.save(commentLike);
        // Redis 记录点赞 (String 记录总数，Set 记录用户)
        redisUtil.sSet(key, userId);
        redisUtil.incr("comment:likeCount:" + commentId, 1);
        //通知被赞用户
        //发送消息
        String message = MessageUtil.getMessage(SystemConstant.SEND_LIKE_MESSAGE, comments.getPublisherId().toString(), "你的评论被点赞啦");
        ConcurrentHashMap<String, WebSocketServer> webSocketMap = WebSocketServer.getWebSocketMap();
        WebSocketServer webSocketServer = webSocketMap.get(comments.getPublisherId().toString());
        //是否在线
        if(webSocketServer!=null){
            try {
                Session session = webSocketServer.getSession();
                if(session!=null){
                    session.getBasicRemote().sendText(message);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        //不管是否在线都先存储未读数
        redisUtil.hincr("user:unread:"+comments.getPublisherId(),"likeMessage",1);
        return Response.success("点赞成功");
    }

    /**
     * 取消点赞评论
     * @param userId
     * @return
     */
    @Override
    public Response<String> cancelLikeComment(Long userId, Long commentId) {
        //先在redis查询是否已点赞
        String key="comment:like:"+commentId;
        //redis取消点赞
        if(redisUtil.sHasKey(key, userId)){
            //取消点赞
            redisUtil.setRemove(key,userId);
            redisUtil.decr("comment:likeCount:"+commentId,1);
        }
        QueryWrapper<CommentLike> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id",userId);
        queryWrapper.eq("comment_id",commentId);
        CommentLike commentLike = this.getOne(queryWrapper);
        if(commentLike == null){
            return Response.error(400,"未点赞");
        }
        //数据库取消点赞(删记录)
        this.removeById(commentLike.getId());
        return Response.success("取消点赞成功");
    }

    /**
     * 查询收到的评论点赞
     * @param userId
     * @return
     */
    @Override
    public Response<List<CommentLikeVO>> receiveLikeComment(Long userId) {
        //查询收到的评论点赞
        QueryWrapper<CommentLike> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("accepter_id",userId);
        queryWrapper.eq("is_deleted",0);
        queryWrapper.orderByDesc("updated_at");
        List<CommentLike> commentLikeList = this.list(queryWrapper);
        //封装对象
        List<CommentLikeVO> commentLikeVOS = BeanUtil.copyToList(commentLikeList, CommentLikeVO.class);
        commentLikeVOS.forEach(commentLikeVO -> {
            Users users = usersMapper.selectById(commentLikeVO.getUserId());
            commentLikeVO.setAvatar(users.getAvatar());
            commentLikeVO.setNickname(users.getNickname());
            //查询评论内容
            Comments comments = commentsMapper.selectById(commentLikeVO.getCommentId());
            commentLikeVO.setContent(comments.getContent());
            commentLikeVO.setVideoId(comments.getVideoId());
        });
        return Response.success(commentLikeVOS);
    }
}


